﻿using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;

namespace System {
    public static class ThemesConfigureServices {
        /// <summary>
        /// 添加Theme服务
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static void AddThemes(this IServiceCollection services) {
            services.AddSingleton<IThemeContext,ThemeContext>();
            //themes support
            services.Configure<RazorViewEngineOptions>(options => {
                options.ViewLocationExpanders.Add(new ThemeableViewLocationExpander());
            });
        }

        /// <summary>
        /// 启用Theme中间件 
        /// appsettings.json文件中配置:AppSetting:Themes 节点
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseThemes(this IApplicationBuilder builder,IConfiguration _configuration) {

            if(!string.IsNullOrWhiteSpace(_configuration["AppSetting:Themes"])) {
                builder.Use(async (context,next) => {
                    context.Response.Headers.Add("Themes",_configuration["Appsetting:Themes"]);
                    await next();
                });
                builder.UseStaticFiles(new StaticFileOptions {
                    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),"Themes")),
                    RequestPath = "/Themes"
                });
            }
            return builder.UseMiddleware<ThemeMiddleware>();
        }
    }
}